package org.xmx0632.connector.codec;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xmx0632.connector.protocol.JsonMessageParser;
import org.xmx0632.connector.protocol.message.Message;
import org.xmx0632.connector.protocol.processor.MessageProcessor;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

/**
 * 
 * Message -> string
 * 
 */
@Component
@Sharable
public class JsonMessageEncoder extends MessageToMessageEncoder<Message> {

	private static final Logger LOG = LoggerFactory.getLogger(JsonMessageEncoder.class);

	@Autowired
	private JsonMessageParser jsonMessageParser;

	@Override
	protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
		String jsonString = jsonMessageParser.toJsonString(msg) + MessageProcessor.CRTL;
		LOG.debug("jsonString:{}", jsonString);
		out.add(jsonString);
	}

	public JsonMessageParser getJsonMessageParser() {
		return jsonMessageParser;
	}

	public void setJsonMessageParser(JsonMessageParser jsonMessageParser) {
		this.jsonMessageParser = jsonMessageParser;
	}

}
